import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/commodity/categories/modal/changePriceAlert/change_price_alert.dart';
import 'package:boss/ui/page/costManagement/widget/cost_management_item.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class MultipleSku {
  int skuId;
  String skuName;
  int price;
  int skuCostPrice;

  MultipleSku({this.skuId, this.skuName, this.price, this.skuCostPrice});
}

class CostManagementList extends StatelessWidget {
  dynamic commodityProvider;
  String cancelButtonText;

  CostManagementList({Key key, this.commodityProvider, this.cancelButtonText}) : super(key: key);

  //记录拆分的多规格菜品sku信息
  List<MultipleSku> multipleSkuArr = [];

  List<Commodity> get storeMenusArr {
    List<Commodity> newArr = [];
    multipleSkuArr = [];
    commodityProvider.storeMenus.forEach((str) {
      if (str.commodityList.length != 0) {
        str.commodityList.forEach((item) {
          if (item.commoditySkuList.length == 0) {
            newArr.add(item);
            multipleSkuArr.add(null);
          } else {
            item.commoditySkuList.forEach((str) {
              newArr.add(item);
              multipleSkuArr.add(MultipleSku(skuId: str.skuId, skuName: str.skuName, price: str.skuPrice, skuCostPrice: str.skuCostPrice));
            });
          }
        });
      }
    });

    return newArr.where((str) => vagueSearch(str.title)).toList() ?? [];
  }

  //搜索模糊过滤
  bool vagueSearch(String title) {
    return (title.indexOf(cancelButtonText) > -1 ? true : false);
  }

  String percentageNum(obj, int index) {
    int _costPrice = multipleSkuArr[index] == null ? (obj.costPrice) : multipleSkuArr[index].skuCostPrice;
//    if(_costPrice==0){ return "无成本";}
    var profit = num.parse((((obj.price - (_costPrice ?? 0)) / obj.price) * 100).toStringAsFixed(2)).toString();

    if (profit.toString().split(".").length == 2) {
      if (profit.toString().split(".")[1] == '0') {
        profit = profit.toString().substring(0, profit.length - 2);
      }
    }
    return "$profit%";
  }

  //设置菜品成本价
  costPriceAdd(BuildContext _context, price, obj, int index) async {
//    print("_____233");
//    print(price);
//    print(obj.id);
//    print(obj.skuId);

    try {
      showLoadingToast();
      var res = await api.batchSetCostPrice({
        'listCommodityCostPriceDetail': [
          {
            "commodityId": obj.id,
            "costPrice": price,
            "skuId": multipleSkuArr[index] == null ? 0 : multipleSkuArr[index].skuId,
          }
        ]
      });
      if (res.successful()) {
        toast("成本价设置成功!");

        try {
          showLoadingToast();
          await commodityProvider?.initData();
        } catch (e) {} finally {
          hideLoadingToast();
          Navigator.pop(_context);
        }
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: ListView.builder(
        padding: EdgeInsets.symmetric(
          horizontal: 50.w,
        ),
        itemBuilder: (context, index) {
          return CostManagementItem(
            title: '${storeMenusArr[index]?.title ?? '--'}${multipleSkuArr[index] == null ? '' : ('（' + multipleSkuArr[index].skuName + '）') ?? ''}',
            subTitle: Padding(
              padding: EdgeInsets.only(
                bottom: 0.w,
              ),
              child: Text(
                "${'售价：¥' + AmountUtil.price2String((multipleSkuArr[index] == null ? storeMenusArr[index]?.price : multipleSkuArr[index].price) ?? 0)}"
                "${(multipleSkuArr[index] != null ? (multipleSkuArr[index].skuCostPrice == -1 ? false : true) : (storeMenusArr[index]?.costPrice == -1 ? false : true)) ? ' 成本：¥' + AmountUtil.price2String((multipleSkuArr[index] == null ? storeMenusArr[index]?.costPrice : multipleSkuArr[index].skuCostPrice) ?? 0) : ''}"
                "${(storeMenusArr[index]?.unit == '' || storeMenusArr[index]?.unit == null) ? '' : ' 单位:' + storeMenusArr[index]?.unit}",
                style: TextStyleConstant().normal_2_26,
              ),
            ),
            childHeight: 62,
            value:
                '${multipleSkuArr[index] == null ? (storeMenusArr[index]?.costPrice == -1 ? '' : '利润率:' + percentageNum(storeMenusArr[index], index)) : (multipleSkuArr[index]?.skuCostPrice == -1 ? '' : '利润率:' + percentageNum(multipleSkuArr[index], index))}',
            onTap: () async {
              showChangePriceAlert(
                context,
                title: '菜品成本价',
                hintText: '请输入菜品成本价',
                initialValue: (multipleSkuArr[index] == null
                    ? ((storeMenusArr[index]?.costPrice == -1 ? null : storeMenusArr[index]?.costPrice) ?? null)
                    : (multipleSkuArr[index].skuCostPrice == -1 ? null : multipleSkuArr[index].skuCostPrice)),
                onConfirm: (e) {
                  costPriceAdd(context, e, storeMenusArr[index], index);
                },
              );
            },
          );
        },
        itemCount: storeMenusArr.length,
      ),
    );
  }
}
